using BW.Mes.WinForms.Common;
using DevExpress.XtraEditors;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BW.Mes.WinForms.Login;

namespace BW.Mes.WinForms.Process.Vue
{
    /// <summary>
    /// Vue页面管理器 - 用于打开Vue页面并传递参数
    /// </summary>
    public static class VuePageManager
    {
        private const string VueBaseUrl = "http://120.26.197.100:8087"; // 默认Vue开发服务器地址
       // private const string VueBaseUrl = "http://localhost:5173"; // 默认Vue开发服务器地址

        /// <summary>
        /// 打开工序流程分配的Vue页面
        /// </summary>
        /// <param name="operationIds">工序ID列表</param>
        /// <param name="title">窗口标题，默认为"工序流程分配"</param>
        /// <returns>返回打开的Vue窗体</returns>
        public static Form OpenProcessAssignmentPage(string selectedId, string title = "工序流程分配")
        {
            try
            {
                // 创建参数对象
                var parameters = new Dictionary<string, object>
                {
                    { "operationIds", selectedId },
                    { "timestamp", DateTime.Now.Ticks }
                };

                // 打开Vue页面
                return OpenVuePage("/workflow-design", parameters, title);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"打开工序流程分配页面失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }

        /// <summary>
        /// 打开工序流程分配的Vue页面 - 单个ID版本
        /// </summary>
        /// <param name="operationId">单个工序ID</param>
        /// <param name="title">窗口标题，默认为"工序流程分配"</param>
        /// <returns>返回打开的Vue窗体</returns>
        public static Form OpenProcessAssignmentPageSingle(string operationId, string title = "工艺流程分配")
        {
            try
            {
                // 创建参数对象
                var parameters = new Dictionary<string, object>
                {
                    { "operationId", operationId },
                    { "timestamp", DateTime.Now.Ticks }
                };

                // 打开Vue页面
                return OpenVuePage("/technology-design", parameters, title);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"打开工序流程分配页面失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }

        /// <summary>
        /// 通用方法：打开Vue页面
        /// </summary>
        /// <param name="path">Vue路由路径</param>
        /// <param name="parameters">传递的参数</param>
        /// <param name="title">窗口标题</param>
        /// <param name="width">窗口宽度</param>
        /// <param name="height">窗口高度</param>
        /// <returns>打开的窗体</returns>
        public static  Form OpenVuePage(string path, object parameters = null, string title = "Vue应用", int width = 1000, int height = 700)
        {
            try
            {
                // 创建一个新的窗体
                var form = new DevExpress.XtraEditors.XtraForm
                {
                    Text = title,
                    Width = width,
                    Height = height,
                    StartPosition = FormStartPosition.CenterScreen
                };

                // 创建WebView2控件
                var webView = new WebView2
                {
                    Dock = DockStyle.Fill
                };
                
                // 将WebView2添加到窗体
                form.Controls.Add(webView);
                
                // 初始化WebView2
                webView.CoreWebView2InitializationCompleted += async (sender, e) => 
                {
                    if (e.IsSuccess)
                    {
                        // 配置WebView2
                        webView.CoreWebView2.Settings.IsScriptEnabled = true;
                        webView.CoreWebView2.Settings.AreDefaultScriptDialogsEnabled = true;
                        webView.CoreWebView2.Settings.IsWebMessageEnabled = true;

                        // 添加Web消息处理
                        webView.CoreWebView2.WebMessageReceived += (s, args) => 
                        {
                            HandleWebMessage(webView, args, form);
                        };
                        
                        // 导航到Vue页面
                        string url = $"{VueBaseUrl}{path}";
                        webView.CoreWebView2.Navigate(url);
                        
                        // 如果有参数，等待页面加载完成后传递
                        if (parameters != null)
                        {
                            webView.NavigationCompleted += async (navSender, navArgs) => 
                            {
                               
                                // 将参数序列化为JSON
                                string paramsJson = JsonConvert.SerializeObject(parameters);
                                
                                //// 设置全局变量
                                //await webView.CoreWebView2.ExecuteScriptAsync(
                                //    $"window.__INITIAL_PARAMS__ = {paramsJson};");

                                // 触发自定义事件通知Vue应用
                                await webView.CoreWebView2.ExecuteScriptAsync(
      $"window.__INITIAL_PARAMS__ = {paramsJson}; " +
      "window.dispatchEvent(new CustomEvent('init-params', { detail: window.__INITIAL_PARAMS__ }));");
                            };
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("WebView2初始化失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                };
                
                // 确保WebView2环境
                _ = InitializeWebViewAsync(webView);
                
                // 显示窗体
                form.Show();

                return form;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"打开Vue页面失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }

        /// <summary>
        /// 初始化WebView2
        /// </summary>
        private static async Task InitializeWebViewAsync(WebView2 webView)
        {
            try
            {
                // 设置用户数据文件夹
                var env = await CoreWebView2Environment.CreateAsync(null, 
                    $"{Application.StartupPath}\\WebView2Data");
                
                // 异步初始化WebView2
                await webView.EnsureCoreWebView2Async(env);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"WebView2初始化失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 处理Web消息
        /// </summary>
        private static async void HandleWebMessage(WebView2 webView, CoreWebView2WebMessageReceivedEventArgs args, Form form)
        {
            try
            {
                var message = JsonConvert.DeserializeObject<dynamic>(args.WebMessageAsJson);
                string type = message.type;
                
                // 处理各种消息类型
                if (type == "closeWindow")
                {
                    form.Invoke(new Action(() => form.Close()));
                }
                else if (type == "getCurrentUser")
                {
                    // 获取当前用户信息
                    var currentUser = BW.Mes.WinForms.Common.RequestUser.CurrentUser;
                    
                    // 创建一个匿名对象，具有相同的结构
                    var anonymousUserInfo = new { message = "未登录" };
                    string userJson;
                    
                    if (currentUser != null)
                    {
                        userJson = JsonConvert.SerializeObject(currentUser);
                    }
                    else
                    {
                        userJson = JsonConvert.SerializeObject(anonymousUserInfo);
                    }
                    
                    // 发送回前端
                    await webView.CoreWebView2.ExecuteScriptAsync(
                        $"window.dispatchEvent(new CustomEvent('user-info', {{ detail: {userJson} }}))");
                }
                else if (type == "getDepartments")
                {
                    // 处理获取部门数据的请求
                    await GetAndSendDepartmentData(webView);
                }
                else if (type == "submitWorkflowAssignment")
                {
                    // 处理工序流程分配结果
                    try
                    {
                        // 获取传递的数据
                        dynamic assignmentData = message.data;
                        
                        // 记录接收到的数据
                        Console.WriteLine($"收到工序流程分配数据: {args.WebMessageAsJson}");
                        
                        // 使用HTTP客户端发送到后端API
                        var result = await SendWorkflowAssignmentToApi(assignmentData);
                        
                        // 如果成功，设置对话框结果并关闭窗口
                        if (result)
                        {
                            form.Invoke(new Action(() => 
                            {
                                form.DialogResult = DialogResult.OK;
                                form.Close();
                            }));
                        }
                        else
                        {
                            form.Invoke(new Action(() => 
                            {
                                XtraMessageBox.Show("工序流程分配失败，请重试。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }));
                        }
                    }
                    catch (Exception ex)
                    {
                        form.Invoke(new Action(() => 
                        {
                            XtraMessageBox.Show($"处理工序流程分配失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }));
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"处理Web消息失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 获取部门数据并发送到前端
        /// </summary>
        private static async Task GetAndSendDepartmentData(WebView2 webView)
        {
            try
            {
                // 忽略SSL证书验证
                var handler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
                };
                
                using (var client = new HttpClient(handler))
                {
                    // 直接请求部门API
                    var response = await client.GetAsync("https://localhost:7222/api/Department/GetAll");
                    
                    if (response.IsSuccessStatusCode)
                    {
                        var content = await response.Content.ReadAsStringAsync();
                        
                        // 日志记录，帮助诊断
                        Console.WriteLine($"部门API响应: {content}");
                        
                        // 将原始JSON直接发送给前端，避免C#端的额外处理
                        await webView.CoreWebView2.ExecuteScriptAsync(@"
                            try {
                                const content = " + content + @";
                                window.dispatchEvent(new CustomEvent('departments-data', { 
                                    detail: { 
                                        data: content
                                    } 
                                }));
                            } catch (error) {
                                console.error('处理部门数据时出错:', error);
                                window.dispatchEvent(new CustomEvent('departments-data', { 
                                    detail: { 
                                        error: '处理部门数据时出错: ' + error.message
                                    } 
                                }));
                            }
                        ");
                    }
                    else
                    {
                        string errorContent = await response.Content.ReadAsStringAsync();
                        await webView.CoreWebView2.ExecuteScriptAsync(
                            $"window.dispatchEvent(new CustomEvent('departments-data', {{ detail: {{ error: '获取部门数据失败: {response.StatusCode} - {errorContent.Replace("'", "\\'")}' }} }}))");
                    }
                }
            }
            catch (Exception ex)
            {
                // 出错时通知前端
                string errorMessage = ex.Message.Replace("'", "\\'");
                await webView.CoreWebView2.ExecuteScriptAsync(
                    $"window.dispatchEvent(new CustomEvent('departments-data', {{ detail: {{ error: '获取部门数据出错: {errorMessage}' }} }}))");
                
                // 本地日志
                Console.WriteLine($"获取部门数据出错: {ex}");
            }
        }

        /// <summary>
        /// 发送工序流程分配数据到API
        /// </summary>
        /// <param name="assignmentData">工序流程分配数据</param>
        /// <returns>操作是否成功</returns>
        private static async Task<bool> SendWorkflowAssignmentToApi(dynamic assignmentData)
        {
            try
            {
                // 忽略SSL证书验证
                var handler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
                };

                // 创建HTTP客户端
                using (var client = new HttpClient(handler))
                {
                    // 设置超时时间
                    client.Timeout = TimeSpan.FromSeconds(30);
                    
                    // 序列化分配数据
                    string jsonContent = JsonConvert.SerializeObject(assignmentData);
                    var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
                    
                    // 发送到API
                    var response = await client.PostAsync("https://localhost:7222/api/Process/AssignProcessToOperations", content);
                    
                    // 检查响应状态
                    if (response.IsSuccessStatusCode)
                    {
                        // 读取响应内容
                        var responseContent = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"工序流程分配API响应: {responseContent}");
                        
                        // 解析API响应
                        var apiResult = JsonConvert.DeserializeObject<dynamic>(responseContent);
                        
                        // 检查API响应状态（假设API返回success=200表示成功）
                        return (int)apiResult.success == 200;
                    }
                    else
                    {
                        Console.WriteLine($"工序流程分配API请求失败: {response.StatusCode} - {response.ReasonPhrase}");
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发送工序流程分配数据时出错: {ex}");
                throw;
            }
        }
    }
} 